import React, { useEffect, useMemo, useState } from 'react';
import {
  Modal,
  Tree,
  Select,
  Tabs,
  Button,
  Row,
  Col,
  TreeSelect,
  Collapse,
  message,
} from 'antd';
import TagsBlock from './components/tagsBlock';
import { filterAssignArr } from '@/utils/tools';
import styles from './index.less';
import { history } from 'umi';
import {
  commonMenuGetByScope,
  ucOrganizationBatchUpdateAuthorization,
} from '@/services/deptControl';
import { formatTreeData, orgGetOne } from '@/services/common';

const { SHOW_PARENT } = TreeSelect;

const { TabPane } = Tabs;
const { Panel } = Collapse;

const DeptAuth: React.FC = () => {
  // 选中机构的数据流
  const [value, setValue] = useState<any>([]);
  // 部门的数据流
  const [department, setDepartment] = useState([]);
  // 子系统数据流
  const [subsystem, setSubsystem] = useState<any[]>([]);
  // 子系统菜单选择
  const [subsystemKey, setSubsystemKey] = useState('');
  // 子系统树形菜单选择数据流
  const [subsystemTreeData, setSubsystemTreeData] = useState<any>({});

  useEffect(() => {
    getDepartmentTreeByRole();
    getSubsystem();
  }, []);

  const checkedKeys = useMemo(() => {
    let arr: any[] = [];
    Object.values(subsystemTreeData).map((item: any) => {
      arr = [...arr, ...item];
    });
    return arr;
  }, [subsystemTreeData]);

  // 初始化组织树
  const getDepartmentTreeByRole = async () => {
    // 根据接口获取值
    const res = await orgGetOne({ isScope: 1 });

    // 写入值
    setDepartment(formatTreeData(res?.data));
  };
  // 初始化子系统数据
  const getSubsystem = async () => {
    const res = await commonMenuGetByScope({
      contain: 2,
      idList: [],
      idType: 2,
      scope: 1,
    });
    console.log(res);

    if (res?.code === 200) {
      setSubsystem(formatTreeData(res?.data) || []);
      setSubsystemKey(res?.data[0]?.id);
    }
  };

  const onChange = (value: any) => {
    console.log('onChange ', value);
    setValue(value);
  };

  const treeCheck = (keys: any) => {
    const arr = { ...subsystemTreeData };
    arr[subsystemKey] = keys;
    setSubsystemTreeData(arr);
  };

  const TreeSelectComponent = (subItem: any) => {
    return (
      <Collapse expandIconPosition="right">
        <Panel header={subItem?.name} key={subItem?.id}>
          <Tree
            onCheck={treeCheck}
            checkedKeys={(subsystemTreeData || {})[subsystemKey] || []}
            checkable
            treeData={subItem?.children}
          />
        </Panel>
      </Collapse>
    );
  };

  const choiceTab = async (key: any) => {
    setSubsystemKey(key);
  };

  const save = async () => {
    const res = await ucOrganizationBatchUpdateAuthorization({
      orgId: value,
      sysFeatureResourceIds: checkedKeys,
    });

    if (res?.code === 200) {
      message.success('组织批量授权成功');
      backList();
    }
  };

  const backList = () => {
    history.push('/features/dept/index');
  };

  return (
    <>
      <div className={styles.authorizationContainer}>
        <div className={styles.functionContainer}>
          <p>选择部门</p>
          <div>
            <Select
              showSearch
              mode="multiple"
              style={{ width: '100%' }}
              placeholder="请选择部门"
              optionFilterProp="children"
              onChange={onChange}
            >
              {department?.map((item: any) => (
                <Select.Option key={item?.serialNo} value={item?.serialNo}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </div>
        </div>
        <div className={styles.specialContainer}>
          <p>功能授权</p>
          <div>
            <Tabs defaultActiveKey={subsystem[0]?.id} onTabClick={choiceTab}>
              {subsystem.map((item: any) => (
                <TabPane tab={item?.name} key={item?.id}>
                  {TreeSelectComponent(item)}
                </TabPane>
              ))}
            </Tabs>
          </div>
        </div>
      </div>
      <div className={styles.actionContainer}>
        <Button onClick={backList}>取消</Button>
        <Button type="primary" onClick={save}>
          保存
        </Button>
      </div>
    </>
  );
};

export default DeptAuth;
